<template>
	<view class="page_list">
		<u-navbar :title="title" :placeholder="true" :autoBack="true">
			<view class="u-nav-slot" slot="right">
				<u-icon name="share-square" size="26" @click="share"></u-icon>
			</view>
		</u-navbar>
		<view v-if="roomList.length != 0" class="list">
			<!-- <view class="list_item" v-for="(item, index) in roomList" :key="index">
				<ListItem :info="item" @click.native="gotoDetails(item)"></ListItem>
			</view> -->
			<checkbox-group v-model="checkedList">
				<view class="list_item" v-for="(item, index) in roomList" :key="index">
					<ListItem :info="item" @click.native="gotoDetails(item)">
						<template slot="topRight">

							<checkbox v-if="showShare" @click.stop="changeChecked(item.id)"></checkbox>

						</template>
					</ListItem>

				</view>
			</checkbox-group>
		</view>
		<view v-else>
			<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
			</u-empty>
		</view>
		<u-loadmore :status="status" v-if="roomList.length != 0" />
		<u-popup :show="showShare" :closeable="true" :overlay="false" mode="bottom" :closeOnClickOverlay="false"
			:customStyle="{borderTop:'1rpx solid #dadada'}" @close="showShare = false">
			<view class="padding">
				<u-checkbox-group v-model="checkboxValue1" placement="row" @change="checkboxChange1">
					<u-checkbox shape="circle" :customStyle="{marginBottom: '20px',marginRight: '20px'}"
						v-for="(item, index) in checkboxList" :key="index" :label="item.label" :name="item.name">
					</u-checkbox>
				</u-checkbox-group>
				<!-- <u--text :text="text"></u--text> -->
				<view class="text_row">
					<view style="width: 60%;">
						已选<text>{{checkedList.length || 0}}</text>套房源
					</view>
					<u-button color="#f05a23" text="分享到好友" style="width: 40%;" @click="shareInfo('WXSceneSession')"
						size="normal"></u-button>
					<u-button color="#3c9cff" text="分享到朋友圈" style="width: 40%; margin-left: 10%;"
						@click="shareInfo('WXSceneTimeline')" size="normal"></u-button>
				</view>
			</view>
		</u-popup>
		<u-popup :show="showQrTips" mode="center" :overlay="true" :round="10" :closeable="true"
			:closeOnClickOverlay="true" @close="showQrTips = false">
			<view style="width: 350px;height:380px;">
				<image :src="qrimgUrl" style="width: 310px;top:3%;height: 310px;left: 5%;"></image>
				<u-button type="warning" size="small" shape="circle" style="width: 50%;height: 35px;font-size: 20px;"
					text="保存到相册" @click="saveImage"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		findARoom
	} from "@/api/index.js"
	import {
		getQrcode
	} from '@/api/home/index.js'
	import ListItem from "./ListItem.vue"
	export default {
		data() {
			return {
				roomList: [],
				checkedList: [],
				checkboxValue1: [],
				qrimgUrl: '',
				checkboxList: [{
						label: '显示小区',
						name: 'community',
					},
					{
						label: '显示租金',
						name: 'rent',
					}
				],
				showShare: false,
				showQrTips: false,
				pageNum: 1,
				status: 'loading',
				title: '地图房源',
				id: null,
				otherInfo: {
					lodgeData: null,
					houseType: null,
					houseLabels: null,
					otherData: null, //其他
					statusData: null, //出租状态
				},
				latitude: null,
				longitude: null,
				radius: 1000,
				communityId: null,
				start: '',
				end: ''
			}
		},
		onLoad(option) {
			const roomInfo = JSON.parse(option.rommInfo);
			console.log(roomInfo);
			if (roomInfo.id) {
				this.communityId = roomInfo.id
				this.title = '小区房源'
			}
			this.otherInfo = roomInfo.otherInfo;
			this.latitude = roomInfo.latitude;
			this.longitude = roomInfo.longitude;
			this.radius = roomInfo.radius;
			this.start = roomInfo.rentForm.start;
			this.end = roomInfo.rentForm.end;
			this.getRoomList()
		},
		components: {
			ListItem
		},
		onReachBottom() {
			this.getRoomList()
		},
		methods: {
			share() {
				this.showShare = !this.showShare
			},
			checkboxChange1(n) {
				this.fliterChecked = n
			},
			shareInfo(type) {

				if (this.checkedList.length == 0) return this.$refs.uToast.show({
					type: "error",
					message: "请选择房源"
				})
				var imgList = []
				this.roomList.map((item, index) => {
					this.checkedList.map((checkedtItem, checkedIndex) => {
						if (item.id == checkedtItem) {
							if (item.mediaUrl) {
								imgList.push(item.mediaUrl)
							}
						}
					})
				})
				let uid = uni.getStorageSync("uid")
				let uname = uni.getStorageSync("uname")
				let phone = uni.getStorageSync("phone")
				let codestr = new Date().valueOf() + ""
				const defaultShareImg =
					"https://dabinhouse-1320826375.cos.ap-shanghai.myqcloud.com/folder/%E6%9A%82%E6%97%A0%E5%9B%BE%E7%89%87.png"
				let shareUrl = encodeURI(this.$h5Url + '?ids=' + this.checkedList.join(',') + '&checkbox=' + this
					.checkboxValue1
					.join(',') + '&uid=' + uid + '&uname=' + uname + '&phone=' + phone + '&time=' + this
					.getNowFormatDate() + "&code=" + this.randomCoding() + codestr.substr(codestr.length - 4, codestr
						.length))
				console.log(shareUrl);
				let base64Url = btoa(unescape(encodeURIComponent(shareUrl)));
				
				uni.share({
					provider: "weixin",
					scene: type,
					type: 0,
					href: shareUrl, //这里写打开app的urlschemes
					// title: `编号${this.randomCoding() + codestr.substr(codestr.length - 4, codestr.length)}为您推荐了${this.checkedList.length}套好房`,
					title: `(编号:${this.randomCoding() + codestr.substr(codestr.length - 4, codestr.length)}）租房找大宾`,
					summary: `管家为您推荐了${this.checkedList.length}套好房, 快来看看吧`,
					imageUrl: imgList[0] || defaultShareImg,
					success: function(res) {
						console.log("success:" + JSON.stringify(res));
					},
					fail: function(err) {
						console.log("fail:" + JSON.stringify(err));
					}
				});
				return
				const res = getQrcode(base64Url)

				if (res.data.code == 200) {
					this.qrimgUrl = res.data.data;
					this.showQrTips = true
				} else {
					this.showQrTips = true;
					this.qrimgUrl = '../static/default/qrError.jpeg'
				}

			},
			randomCoding() {
				//创建26个字母数组
				var arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
					'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
				];
				var idvalue = '';
				let n = 2; //这个值可以改变的，对应的生成多少个字母，根据自己需求所改
				for (var i = 0; i < n; i++) {
					idvalue += arr[Math.floor(Math.random() * 26)];
				}
				return idvalue;
			},
			saveImage() {
				const qrImageNetAddr = this.qrimgUrl;
				// 先下载二维码
				uni.downloadFile({
					url: qrImageNetAddr,
					success: (res) => {
						const that = this
						if (res.statusCode === 200) {
							// 关闭loading
							//  uni.hideLoading()
							// 保存视频到手机相册
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									// 成功提示

									uni.showToast({
										title: '保存成功',
										icon: 'none'
									})
									//this.showQrTips=false;

								}
							})
						}

					}
				})
			},
			//获取当前日期函数
			getNowFormatDate() {
				let date = new Date(),
					obj = {
						year: date.getFullYear(), //获取完整的年份(4位)
						month: date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
						strDate: date.getDate(), // 获取当前日(1-31)
						hour: date.getHours(), //获取当前小时(0 ~ 23)
						minute: date.getMinutes(), //获取当前分钟(0 ~ 59)
						second: date.getSeconds() //获取当前秒数(0 ~ 59)
					}
				Object.keys(obj).forEach(key => {
					if (obj[key] < 10) obj[key] = `0${obj[key]}`
					// console.log(obj[key])
				})

				return `${obj.year}-${obj.month}-${obj.strDate}-${obj.hour}:${obj.minute}:${obj.second}`
			},
			changeChecked(id) {

				if (this.checkedList.indexOf(id) != -1) {

					this.checkedList.map((item, index) => {

						if (item == id) {
							this.checkedList.splice(index, 1)
						}
					})
				} else {
					this.checkedList.push(id)
				}

			},
			async getRoomList() {
				if (this.status == 'nomore') return

				let loadding = uni.showLoading({
					title: '加载中……'
				})
				const res = await findARoom({
					"pageNum": this.pageNum, //页码 //必传
					"pageSize": 10, //每页条目数 //必传
					"longitude": this.longitude, //经度 必须传
					"latitude": this.latitude, //纬度 必须传
					"radius": this.radius, //半径，米为单位 必须传
					rentalBegin: this.start, //租金起
					rentalEnd: this.end,	
					communityId: this.communityId,
					"rentalType": this.otherInfo.lodgeData, //0合租，1整租
					"houseType": this.otherInfo.houseType, // 1室  2室  3室  4室以上
					"rentState": this.otherInfo.statusData, //0 未租 1已租
					"otherData": this.otherInfo.otherData, //1 二四小时  , 2 个人 , 3 有图  , 4 无图
					"houseLabels": this.otherInfo.houseLabels
				})
				if (res.data.code != 200) {
					uni.hideLoading(loadding)
					this.$refs.uToast.show({
						type: 'error',
						message: res.data.msg
					})

					return
				}
				this.roomList.push(...res.data.rows)
				// console.log(this.roomList);
				if (this.communityId) {
					this.title = this.roomList[0].communityName
				}
				if (this.roomList.length == res.data.total) {

					this.status = 'nomore'
				} else {
					this.pageNum += 1
				}
				uni.hideLoading(loadding)
			},
			computedTagNumver(tagLIst) {
				if (tagLIst.length < 8) return tagLIst
				var arr = tagLIst
				return arr.slice(0, 8)
			},

			gotoDetails(item) {
				uni.navigateTo({
					url: '/pages/home/details?id=' + item.id
				})
			},
		},
	}
</script>

<style scoped lang="scss">
	@import "@/styles/global.scss";
	@import "@/styles/index.scss";

	.page_list {
		width: 100%;
		height: 100vh;

		.padding {
			padding: 30rpx;

			.text_row {
				@include flexBetween;
				margin-top: 40rpx;
				font-size: 30rpx;

				text {
					font-weight: bold;
					color: $theme;
					font-size: 40rpx;
				}
			}
		}



		.list {
			padding: 0 20rpx;
			box-sizing: border-box;
		}

		// background-color: red;
	}

	.item_wrapper {
		border-bottom: 1px solid #eee;
		margin: 10px 0;
		padding-bottom: 10px;
		// height: 100vh;

		.top {
			display: flex;
			align-items: center;
			// overflow: hidden;

			.left {
				padding-right: 20rpx;

				.update {
					color: white;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 26rpx;
					width: auto;
					padding: 10rpx;
					height: auto;
					background-color: #71736d;
					opacity: 0.6;
					position: relative;
					top: -25rpx;
				}
			}

			.right {
				margin-top: -40rpx;

				.tag_wrp {

					// max-height: 165rpx;
					width: 100%;
					height: auto;
					// line-clamp: 2;
					// overflow: hidden;
					text-overflow: ellipsis;

					// white-space: nowrap;  
					.tag_name {
						display: inline-block;
						margin: 2rpx;
					}
				}

				.money {
					display: flex;
					justify-content: flex-start;
					align-items: flex-end;
				}
			}
		}

		.bottom {
			display: flex;
			justify-content: flex-end;
		}

	}
</style>